package test5;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UDPReciver {
    public static void main(String[] args) {
        //声明数据报
        DatagramPacket dp = null;
        //声明数据包套接字
        DatagramSocket ds = null;
        Scanner input = new Scanner(System.in);

        try {
            ds = new DatagramSocket(8888);
            byte[] buf = new byte[1024];
            //接收发送方送过来的数据包

            while (true) {
                dp = new DatagramPacket(buf, buf.length);
                ds.receive(dp);
                //解析数据bao
                String mess = new String(dp.getData(), 0, dp.getLength());
                InetAddress ia = dp.getAddress();
                System.out.println(ia.getHostAddress() + "说:" + mess);

                mess = input.nextLine();
                byte[] datas = mess.getBytes();
                dp = new DatagramPacket(datas,datas.length,dp.getSocketAddress());
                ds.send(dp);

            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ds.close();
        }
    }





}
